<template>
  <a-card style="margin-top:24px;">
    <a-row :gutter="24">
      <!-- 字典树展示 -->
      <a-col :span="4" style="height:100%;">
        <div class="catalogue">
          <a-tree
            :defaultExpandedKeys="[-1]"
            :defaultExpandAll="true"
            :tree-data="dictCatalogue"
            @select="handleTreeSelect"
          />
        </div>
      </a-col>

      <a-col :span="20">
        <!-- 查询区域 -->
        <div>
          <a-form layout="horizontal" :labelCol="{ span: 8 }" :wrapperCol="{ span: 15 }">
            <a-row>
              <a-col :md="5" :sm="24">
                <a-form-item label="字典名称">
                  <a-input
                    v-model="searchForm.name"
                    :allowClear="true"
                    placeholder="字典名称"
                    @keyup.enter="getList"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-item label="字典值">
                  <a-input
                    v-model="searchForm.value"
                    :allowClear="true"
                    placeholder="字典值"
                    @keyup.enter="getList"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item>
                  <a-button v-permission="`basic:dict:list`" type="primary" @click="getList"
                    >查询</a-button
                  >
                  <a-button class="ml-8" @click="handleReset">重置</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <!-- 表格区域 -->
        <div>
          <div class="operator">
            <a-button v-permission="`basic:dict:add`" class="mr-8" type="primary" @click="handleAdd"
              >新增</a-button
            >
            <a-button
              v-permission="`basic:dict:batchDel`"
              :class="{ 'btn-disabled': !rowSelection.selectedRowKeys.length }"
              type="danger"
              @click="handleDelAll"
              >批量删除</a-button
            >
          </div>

          <div style="margin:16px 0;">
            <!-- <a-popover
              placement="bottom"
              overlayClassName="columns-select"
              title="列选择"
              :arrowPointAtCenter="true"
              trigger="click"
            >
              <a-icon class="icon-table" type="table" />
              <template slot="content">
                <a-checkbox-group
                  class="check-group"
                  v-model="colList"
                  name="checkboxgroup"
                  :options="columnsOptions"
                  @change="handleColChange"
                />
              </template>
            </a-popover> -->
          </div>

          <a-table
            bordered
            :loading="loading"
            :row-key="item => item.id"
            :columns="columns"
            :data-source="dicList"
            :pagination="pagination"
            :rowSelection="rowSelection"
            @change="getList"
          >
            <span slot="action" slot-scope="item">
              <a v-permission="`basic:dict:update`" @click="handleEdit(item)">修改</a>
              <a-divider type="vertical" />
              <a v-permission="`basic:dict:del`" class="text-danger" @click="handleDel(item)"
                >删除</a
              >
            </span>
          </a-table>
        </div>
      </a-col>
    </a-row>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form" v-bind="formItemLayout">
        <a-form-item label="字典名称">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '字典名称不能为空' }] }]"
            placeholder="字典名称"
          />
        </a-form-item>
        <a-form-item label="字典类型">
          <a-input
            v-decorator="['type', { rules: [{ required: true, message: '字典类型不能为空' }] }]"
            placeholder="字典类型"
          />
        </a-form-item>
        <a-form-item label="字典码">
          <a-input
            type="number"
            v-decorator="['code', { rules: [{ required: true, message: '字典码不能为空' }] }]"
            placeholder="注意：同一字典类型下的字典码需要唯一"
          />
        </a-form-item>
        <a-form-item label="字典值">
          <a-input
            v-decorator="['value', { rules: [{ required: true, message: '字典值不能为空' }] }]"
            placeholder="字典值"
          />
        </a-form-item>
        <a-form-item label="排序">
          <a-input type="number" v-decorator="['orderNum', { rules: [] }]" placeholder="排序值" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { basicService } from '@/services';

const originColumns = [
  {
    title: '字典名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '字典类型',
    dataIndex: 'type',
    key: 'type',
    align: 'center',
  },
  {
    title: '字典码',
    dataIndex: 'code',
    key: 'code',
    align: 'center',
  },
  {
    title: '字典值',
    dataIndex: 'value',
    key: 'value',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
  },
];

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'basicDict',

  data() {
    return {
      formItemLayout,
      originColumns,
      columns: [],
      columnsOptions: [], // 可选的表格列
      colList: [], // 表格列筛选
      // 搜索表单
      searchForm: {
        name: '',
        value: '',
        type: '',
      },
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ['10', '50', '100', '200'],
        showQuickJumper: true,
        showTotal: total => `共${total}条`,
        current: 1,
        pageSize: 10,
        total: 0,
      },
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      form: this.$form.createForm(this, { name: 'dic-form' }),
      confirmLoading: false,
      selectedItem: null,
      deptTreeData: [],
      dictCatalogue: [
        {
          key: -1,
          title: '字典列表',
          children: [],
        },
      ],
      dicList: [],
      selectedDict: null, // 选中的树节点
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },
  },

  created() {
    this.getCatalogue();
    this.getList();

    // 初始化表格列
    this.columns = this.originColumns;
    this.columnsOptions = this.originColumns.map(item => {
      return {
        label: item.title,
        value: item.key,
      };
    });
    this.colList = originColumns.map(c => c.key);
  },

  methods: {
    // 重置
    handleReset() {
      this.searchForm = {
        name: '',
        value: '',
        type: '',
      };
    },

    // 表格列筛选
    handleColChange(val) {
      console.log(val);
      this.columns = this.originColumns.filter(col => {
        return val.includes(col.key);
      });
    },

    handleTreeSelect(selectedKeys) {
      console.log(selectedKeys);
      if (selectedKeys && selectedKeys.length) {
        const dictId = selectedKeys[0];
        const dictItem = this.dictCatalogue[0].children.find(dict => dict.key === dictId);
        this.searchForm.name = dictItem.title;
        this.selectedDict = dictItem;
      } else {
        this.searchForm.name = '';
        this.selectedDict = null;
      }
    },

    // 新增
    handleAdd() {
      this.type = 1;
      this.visible = true;
      if (this.selectedDict) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            name: this.selectedDict.title,
            type: this.selectedDict.type,
          });
        });
      }
    },

    // 批量删除
    handleDelAll() {
      if (!this.rowSelection.selectedRowKeys.length) return;
      console.log('批量删除', this.rowSelection.selectedRowKeys);
      const that = this;
      const idList = this.rowSelection.selectedRowKeys;

      this.$confirm({
        title: '确认删除吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return new Promise(resolve => {
            basicService
              .delDictList({ idList })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getCatalogue();
                  that.getList();
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 删除
    handleDel(item) {
      const { id } = item;

      const that = this;
      this.$confirm({
        title: '确认删除该字典值吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return new Promise(resolve => {
            basicService
              .delDict({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getCatalogue();
                  that.getList();
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改
    handleEdit(item) {
      console.log(item);
      const { id } = item;
      basicService.getDictDetail({ id }).then(res => {
        if (res.code === '200') {
          const { name, type, code, value, orderNum } = res.data;
          this.$nextTick(() => {
            this.form.setFieldsValue({ name, type, code, value, orderNum });
          });
        }
      });

      this.type = 2;
      this.visible = true;
      this.selectedItem = item;
    },

    // 取消新建/修改
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },

    // 新建/修改确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            basicService
              .addDict(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.visible = false;
                  this.form.resetFields();
                  this.$message.success('操作成功');
                  this.getCatalogue();
                  this.getList();
                }
              })
              .catch(e => {
                console.log(e);
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            basicService
              .updateDict({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getList();
                }
              })
              .catch(e => {
                console.log(e);
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 获取字典目录
    getCatalogue() {
      basicService.getDictCatalogue({}).then(res => {
        if (res.code === '200') {
          const children = res.data.items.map(item => {
            return {
              key: item.id,
              title: item.name,
              type: item.type,
            };
          });
          this.dictCatalogue[0].children = children;
        }
      });
    },

    // 获取字典列表
    getList() {
      this.loading = true;

      const params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...this.searchForm,
      };

      basicService.getDictList(params).then(res => {
        console.log(res);
        this.dicList = res.data.content;
        this.pagination.total = res.data.totalElements;
        this.loading = false;
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
